﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DeviceManagement;
using System.Threading;

namespace WindowsFormsSample
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			LoadDevices();
		}

		private void LoadDevices()
		{
			var model = LoadDeviceSetModel();

			treeView1.Nodes.Clear();
			treeView1.ImageList = this.imageList1;


			DeviceImageList deviceImageList = new DeviceImageList(this.imageList1);

			var deviceClasses = (from x in model.Classes orderby x.DisplayName select x);
			foreach (var deviceClass in deviceClasses)
			{	
				int deviceClassImageIndex = deviceImageList.GetImage(deviceClass.ClassGuid);
				TreeNode groupNode = new TreeNode() { Text = deviceClass.DisplayName, ImageIndex = deviceClassImageIndex, SelectedImageIndex = deviceClassImageIndex };
				
				var devices = (from x in deviceClass.Devices orderby x.DisplayName select x);
				foreach (var device in devices)
				{
					int deviceImageIndex = deviceImageList.GetImage(device.ClassGuid);
					TreeNode deviceNode = new TreeNode() { Text = device.DisplayName, ImageIndex = deviceImageIndex, SelectedImageIndex = deviceImageIndex };
					groupNode.Nodes.Add(deviceNode);
				}

				treeView1.Nodes.Add(groupNode);
			}
		}

		private static DeviceSetModel LoadDeviceSetModel()
		{
			var model = new DeviceSetModel();
			using (DeviceInfoSet set = DeviceInfoSet.GetAllClassesPresent())
			{
				IEnumerable<DeviceInfo> devices = set.GetDevices();
				DeviceEqualityComparer comparer = new DeviceEqualityComparer(DeviceComparisonFlag.ClassGuid);
				model.Classes = devices.Distinct(comparer).Select<DeviceInfo, DeviceClassModel>((x) => new DeviceClassModel()
				{
					ClassGuid = x.ClassGuid,
					DisplayName = DeviceInfoSet.GetClassDescription(x.ClassGuid),
					Devices = devices.Where((dev) => dev.ClassGuid == x.ClassGuid).Select<DeviceInfo, DeviceModel>((dev) => new DeviceModel()
					{	ClassGuid = dev.ClassGuid,
						DeviceInstanceId = dev.DeviceInstanceId,
						DisplayName = dev.FriendlyName ?? dev.Description
					}).ToList()
				}).ToList();

				Thread.CurrentThread.Join(50);

			}

			return model;
		}

	}
}
